<!DOCTYPE html>
<html>

<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
	<meta name="theme-color" content="#33474d">
	<title>CSRF攻击防范 | 失落的乐章</title>
	<link rel="stylesheet" href="/css/style.css" />
	
      <link rel="alternate" href="/atom.xml" title="失落的乐章" type="application/atom+xml">
    
</head>

<body>

	<header class="header">
		<nav class="header__nav">
			
				<a href="/archives" class="header__link">Archive</a>
			
				<a href="/tags" class="header__link">Tags</a>
			
				<a href="/atom.xml" class="header__link">RSS</a>
			
		</nav>
		<h1 class="header__title"><a href="/">失落的乐章</a></h1>
		<h2 class="header__subtitle">技术面前，永远都是学生。</h2>
	</header>

	<main>
		<article>
	
		<h1>CSRF攻击防范</h1>
	
	<div class="article__infos">
		<span class="article__date">2017-10-12</span><br />
		
		
			<span class="article__tags">
			  	<a class="article__tag-link" href="/tags/Linux安全/">Linux安全</a>
			</span>
		
	</div>

	

	
		<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;CSRF攻击必须依次完成以下两个条件： </p>
<ol>
<li>登录受信任网站A，并在本地生成Cookie。 </li>
<li>在不登出A的情况下，访问危险网站B。</li>
</ol>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;关闭浏览器不能结束一个会话，但大多数人都会错误的认为关闭浏览器就等于退出登录/结束会话了</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;CSRF攻击形成的原因： </p>
<ol>
<li>网站违反了HTTP协议，使用GET请求更新资源(非常危险). </li>
<li>使用无校验的表单</li>
</ol>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;CSRF攻击是源于WEB的隐式身份验证机制！(比如你在A网站登录后,在同一个浏览器的tab页打开B网站网页, 而B网站网页有一些脚本链接到A网站并偷偷的发送请求更新你账号的信息.如果没有防CSRF攻击,这样是可以实现的.) </p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;WEB的身份验证机制虽然可以保证一个请求是来自于某个用户的浏览器，但却无法保证该请求是用户批准发送的！</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;CSRF防范方式：客户端页面增加伪随机数。每次需要修改该用户的数据库信息时必须带上该随机数,否则不受理.</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;解决办法: 在Form表单加一个hidden field，里面是服务端生成的足够随机数的一个Token(恶意网站猜不到也无法获取到相同的Token), 然后使用一个拦截器interceptor来检查每一个非get请求, 看该token与服务器token是否一致,不一致的不受理该请求. </p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;以下是token 的工具管理类:</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div></pre></td><td class="code"><pre><div class="line">package com.xxx.xxx.util;</div><div class="line"></div><div class="line">import javax.servlet.http.HttpServletRequest;</div><div class="line">import javax.servlet.http.HttpSession;</div><div class="line">import java.util.UUID;</div><div class="line"></div><div class="line"></div><div class="line">/**</div><div class="line"> * CSRFtoken管理类</div><div class="line"> *</div><div class="line"> * @author 作者  yss</div><div class="line"> * @version 版本号 v1.0</div><div class="line"> */</div><div class="line">public final class CSRFTokenManager &#123;</div><div class="line"></div><div class="line"></div><div class="line">    /**</div><div class="line">     * 约定规范：表单提交时的token的input的name属性必须为该值才能获取到后台返回的token。</div><div class="line">     * 下面是使用EL表达式接收从后台返回的token参数</div><div class="line">     * 如: &lt;input <span class="built_in">type</span>=<span class="string">"hidden"</span> id=<span class="string">"CSRFToken"</span> value=<span class="string">"<span class="variable">$&#123;CSRFToken&#125;</span>"</span>&gt;</div><div class="line">     */</div><div class="line">    public static final String CSRF_PARAM_NAME = <span class="string">"CSRFToken"</span>;</div><div class="line"></div><div class="line">    /**</div><div class="line">     * 存放在session中的token名称(跟上面的name属性值不一定一样)</div><div class="line">     */</div><div class="line">    public static final String CSRF_TOKEN_FOR_SESSION_ATTR_NAME = CSRFTokenManager.class.getName() + <span class="string">".tokenval"</span>;</div><div class="line"></div><div class="line">    /**</div><div class="line">     *从session中获取token字符串</div><div class="line">     * @param session</div><div class="line">     * @<span class="built_in">return</span></div><div class="line">     */</div><div class="line">    public static String getTokenForSession(HttpSession session) &#123;</div><div class="line">        String token = null;</div><div class="line">        //保证session只存在一个token，避免多线程情况下产生冲突。</div><div class="line">        synchronized (session) &#123;</div><div class="line">            token = (String) session.getAttribute(CSRF_TOKEN_FOR_SESSION_ATTR_NAME);//尝试获取session中的token</div><div class="line">            <span class="keyword">if</span> (null == token) &#123;//如果session中没有token，就重新生成一个token</div><div class="line">                token = UUID.randomUUID().toString();</div><div class="line">                session.setAttribute(CSRF_TOKEN_FOR_SESSION_ATTR_NAME, token);</div><div class="line">            &#125;</div><div class="line">        &#125;</div><div class="line">        <span class="built_in">return</span> token;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    /**</div><div class="line">     *获取到request中的token值。</div><div class="line">     * @param request</div><div class="line">     * @<span class="built_in">return</span></div><div class="line">     */</div><div class="line"></div><div class="line">    public static String getTokenFromRequest(HttpServletRequest request) &#123;</div><div class="line">        <span class="built_in">return</span> request.getParameter(CSRF_PARAM_NAME);</div><div class="line">    &#125;</div><div class="line">//构造器</div><div class="line">    private <span class="function"><span class="title">CSRFTokenManager</span></span>() &#123;</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;后台返回token参数给页面:</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;String token = CSRFTokenManager.getTokenForSession(request.getSession());//uuid生成的随机token</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;modelAndView.addObject(CSRFTokenManager.CSRF_PARAM_NAME, token);//添加token参数 <input type="hidden" id="CSRFToken" value="${CSRFToken}">&lt;%–token–%&gt;</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;编写代码要符合HTTP规范,不要使用GET请求更新资源 </p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;在非GET请求中带上token 参数(ajax请求也要),然后使用拦截器检查. </p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;对于受到CSRF攻击使用的是抛自定义异常,然后使用springmvc全局异常进行处理</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div></pre></td><td class="code"><pre><div class="line">package com.xxx.xxx.interceptor;</div><div class="line"></div><div class="line">import com.xxx.xxx.exception.CSRFException;</div><div class="line">import com.xxx.xxx.util.CSRFTokenManager;</div><div class="line">import org.springframework.web.servlet.ModelAndView;</div><div class="line">import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;</div><div class="line"></div><div class="line">import javax.servlet.http.HttpServletRequest;</div><div class="line">import javax.servlet.http.HttpServletResponse;</div><div class="line"></div><div class="line">/**</div><div class="line"> * 对于未登录用户的请求进行拦截,确保用户已经登录,然后进行后续的网页请求</div><div class="line"> *</div><div class="line"> * @Author yss</div><div class="line"> * @Version 1.0</div><div class="line"> * @see</div><div class="line"> */</div><div class="line">public class CSRFInterceptor extends HandlerInterceptorAdapter &#123;</div><div class="line"></div><div class="line">    @Override</div><div class="line">    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception &#123;</div><div class="line">//        Enumeration parasm = request.getParameterNames();</div><div class="line">        <span class="keyword">if</span> (!<span class="string">"GET"</span>.equals(request.getMethod())) &#123;//非get请求</div><div class="line">            String CSRFToken = CSRFTokenManager.getTokenFromRequest(request);//页面传过来的csrf参数</div><div class="line">            <span class="keyword">if</span> (CSRFToken == null || !CSRFToken.equals(CSRFTokenManager.getTokenForSession(request.getSession()))) &#123;//token不对应</div><div class="line">                throw new CSRFException(<span class="string">"CSRF攻击"</span>);//抛异常后将会进入springmvc全局异常处理体系</div><div class="line">            &#125;</div><div class="line">        &#125;</div><div class="line">        <span class="built_in">return</span> <span class="literal">true</span>;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    @Override</div><div class="line">    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception &#123;</div><div class="line">        super.postHandle(request, response, handler, modelAndView);</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;在spring的配置文件中添加拦截器使其生效</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line">&lt;mvc:interceptors&gt;</div><div class="line">    &lt;!-- 防止CSRF攻击的拦截器 --&gt;</div><div class="line">    &lt;mvc:interceptor&gt;</div><div class="line">        &lt;mvc:mapping path=<span class="string">"/**"</span>/&gt;</div><div class="line">        &lt;bean id=<span class="string">"CSRFInterceptor"</span> class=<span class="string">"com.xxx.xxx.interceptor.CSRFInterceptor"</span>&gt;&lt;/bean&gt;</div><div class="line">    &lt;/mvc:interceptor&gt;</div><div class="line">&lt;/mvc:interceptors&gt;</div></pre></td></tr></table></figure>

	

	
		<span class="different-posts"><a href="/2017/10/12/Linux安全/1. CSRF攻击防范/" onclick="window.history.go(-1); return false;">⬅️ Go back </a></span>

	

</article>

	</main>

	<footer class="footer">
	<div class="footer-content">
		
	      <div class="footer__element">
	<p>Hi there, <br />welcome to my Blog glad you found it. Have a look around, will you?</p>
</div>

	    
	      <div class="footer__element">
	<h5>Check out</h5>
	<ul class="footer-links">
		<li class="footer-links__link"><a href="/archives">Archive</a></li>
		
		  <li class="footer-links__link"><a href="/atom.xml">RSS</a></li>
	    
		<li class="footer-links__link"><a href="/about">about page</a></li>
		<li class="footer-links__link"><a href="/tags">Tags</a></li>
		<li class="footer-links__link"><a href="/categories">Categories</a></li>
	</ul>
</div>

	    

		<div class="footer-credit">
			<span>© 2017 失落的乐章 | Powered by <a href="https://hexo.io/">Hexo</a> | Theme <a href="https://github.com/HoverBaum/meilidu-hexo">MeiliDu</a></span>
		</div>

	</div>


</footer>



</body>

</html>
